# -*- coding: utf-8 -*-
import requests
import json
import configparser
import os
import logging

logger = logging.getLogger('django')

class WeChat(object):

    def __init__(self, touser=None, toparty=None, totag=None, agentid=None):
        root_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))  # 获取当前运行文件所在目录
        configpath = os.path.join(root_dir, "config.ini")
        cf = configparser.ConfigParser()
        cf.read(configpath)  # 读取配置文件
        url = cf.get('basegateway', 'url')
        self.url = url
        self.touser = touser
        self.toparty = toparty
        self.totag = totag
        self.agentid = agentid

    def get_access_token(self):
        access_token = self.rpc_resource_pull('qyweixin_access_token')
        return access_token
    '''
        获取XwjrRpc服务的公共资源接口
        如:企业微信access_token等
    '''

    def rpc_resource_pull(self, resource_key):
        if resource_key is None or resource_key is '':
            return ''
        req_data = {
            'pull_resource': resource_key
        }
        res_data = requests.post(self.url, data=req_data)
        data_value = res_data.json()[resource_key]
        return data_value

    def send_markdown(self, content):
        access_token = self.get_access_token()
        url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=%s" % access_token
        data = {
            "touser": self.touser,
            "toparty": self.toparty,
            "totag": self.totag,
            "agentid": self.agentid,
            "msgtype": "markdown",
            "markdown": {
                "content": content
            },
            "enable_duplicate_check": 0
        }
        logger.info("request url: %s" % url)
        logger.info("post data: %s" % data)
        r = requests.post(url=url, data=json.dumps(data))
        res = r.json()
        if str(res['errcode']) != '0':
            r = requests.post(url=url, data=json.dumps(data))
            res = r.json()
            if str(res['errcode']) != '0':
                raise SystemError(res)
        return r.json()
